package com.ykyl.controller.security;


import com.alibaba.fastjson.JSONObject;
import com.ykyl.base.PageResponse;
import com.ykyl.base.Result;
import com.ykyl.pojo.dto.UserDto;
import com.ykyl.pojo.vo.UserVo;
import com.ykyl.service.UserService;
import com.ykyl.utils.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户前端控制器
 */
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    /***
     *  多条件查询用户分页列表
     * @param userDto 用户DTO查询条件
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @return: Page<UserVo>
     */
    @PostMapping("page/{pageNum}/{pageSize}")
    public Result<PageResponse<UserVo>> findUserVoPage(
                                    @RequestBody UserDto userDto,
                                    @PathVariable("pageNum") int pageNum,
                                    @PathVariable("pageSize") int pageSize) {
        PageResponse<UserVo> userVoPage = userService.findUserPage(userDto, pageNum, pageSize);
        return Result.success(userVoPage);
    }

    /**
     *  保存用户
     * @param userDto 用户Vo对象
     * @return UserDto
     */
    @PutMapping
    public Result<UserVo> createUser(@RequestBody UserDto userDto) {
        UserVo userVoResult = userService.createUser(userDto);
        return Result.success(userVoResult);
    }
    /**
     *  修改用户
     * @param userId 用户Vo对象
     * @return Boolean 是否修改成功
     */
    @PostMapping("reset-passwords/{userId}")
    public Result<Boolean> resetPasswords(@PathVariable("userId") String userId) {
        Boolean flag = userService.resetPasswords(userId);
        return Result.success(flag);
    }


    /**
     *  修改用户
     * @param userDto 用户DTO对象
     * @return Boolean 是否修改成功
     */
    @PatchMapping
    public Result<Boolean> updateUser(@RequestBody UserDto userDto) {
        Boolean flag = userService.updateUser(userDto);
        return Result.success(flag);
    }

    /***
     *  多条件查询用户列表
     * @param userVo 用户Vo对象
     * @return List<UserVo>
     */
    @PostMapping("list")
    public Result<List<UserVo>> userList(@RequestBody UserVo userVo) {
        List<UserVo> userVoList = userService.findUserList(userVo);
        return Result.success(userVoList);
    }

    @GetMapping("current-user")
    Result<UserVo> findCurrentUser()  {
        String subject = UserThreadLocal.getSubject();
        UserVo userVo = JSONObject.parseObject(subject,UserVo.class);
        return Result.success(userVo);
    }


    @DeleteMapping("/remove/{userIds}")
    public Result remove(@PathVariable List<Long> userIds) {
        return Result.success(userService.deleteUserByIds(userIds));
    }
}
